"""
mysql_views.py: 研究的是model和mysql的交互
"""

from flask import Blueprint
from .models import *  # 这里需要导入model

mysql_blue = Blueprint("mysql", __name__)  # 创建蓝图


# mysql蓝图
@mysql_blue.route("/")
def index():
    return "model success"


# 新增
@mysql_blue.route("/add/")
def add():
    user = User()
    user.name = "熊大"
    user.age = 18
    user.sex = True
    user.salary2 = 15000
    db.session.add(user)  # 将user对象添加到session中
    db.session.commit()  # 将数据同步到数据库中
    return "success"


users = []
@mysql_blue.route("/mul-add/")
def mul_add():
    for i in range(10,30):
       user = User()
       user.name="冰冰"+str(i)
       user.age = 18
       user.sex = True
       user.salary2 = 15000
       users.append(user)

    try:
       db.session.add_all(users) # 批量提交
       db.session.commit() # 提交事务
    except Exception as e:
       db.session.rollback() # 事务回滚
       db.session.flush()
       return str(e)
    return  "success-mul"



@mysql_blue.route("/delete/")
def delete():
    user=User.query.first() # 查询到第一条数据
    db.session.delete(user) # 删除数据
    db.session.commit() # 提交事务
    return "success"


@mysql_blue.route("/update/")
def update():
    user=User.query.first() # 查询到第一条数据
    user.age=455
    user.name="啊啊啊啊"
    db.session.commit()
    return "success"



@mysql_blue.route("/select/")
def select():
    users=User.query.all()
    print(users)
    print(User.query)
    return  "success"